package com.packer.ext.rx;

import android.util.Log;
import com.packer.ext.http.BaseRespose;
import com.packer.ext.http.ServerException;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by hpb on 2018/4/11.
 */
public class RxHelper {
  /**
   * 对服务器返回数据进行预处理
   *
   */
  public static <T> ObservableTransformer<BaseRespose<T>, T> handleResult(
          final ICustomLifecycleProvider lifecycleProvider) {
    return new ObservableTransformer<BaseRespose<T>, T>() {
      @Override
      public Observable<T> apply(Observable<BaseRespose<T>> tObservable) {
        return tObservable.flatMap(new Function<BaseRespose<T>, Observable<T>>() {
          @Override
          public Observable<T> apply(final BaseRespose<T> result) {
            Log.d("RxHelper", "result from api : " + result);
            if (result.succeed()) {
              return Observable.create(new ObservableOnSubscribe<T>() {
                @Override public void subscribe(ObservableEmitter<T> observableEmitter)
                    throws Exception {
//                  observableEmitter.onNext(result.data);
                  observableEmitter.onNext(result.results);
                  observableEmitter.onComplete();
                }
              });
            } else {
              return Observable.error(new ServerException(result.msg));
            }
          }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(lifecycleProvider.<T>bindToDestroyEvent());
      }
    };
  }

  /**
   * 线程切换
   * @return
   */
  public static   <T> ObservableTransformer<T, T> io_main() {
    return new ObservableTransformer<T, T>() {
      @Override
      public ObservableSource<T> apply(Observable<T> observable) {
        return observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
      }
    };
  }
}
